package com.sosee.cgfw.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.FriendsData;
import com.sosee.cgfw.entity.FriendsJson;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thinkpad on 2016/2/24.
 * 转赠activity
 */
public class DonationActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener {
    private HttpUtils httpUtils;

    String[] letter={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    String[] cityLetter={"C","B","H","G","W","C","S","S","C","W","H","Z","C","D","N","L","Q","S","S"
            ,"L","N","H","X","H","S","Z","G","N","J","T","S","X","A"};
    String[] cityName={"长沙","北京","杭州","广州","武汉","重庆","上海","深圳","长春","乌鲁木齐","哈尔滨","郑州","成都","大连","南昌","兰州","齐齐哈尔","汕头","苏州"
            ,"拉萨","南京","呼和浩特","厦门","合肥","沈阳","张家界","贵州","宁夏","济南","天津","石家庄","西安","澳门"};
    List<String> letterToCity=new ArrayList<String>();
    int count;
    ListView lv;

    ListView lv1;
    private Map<String,String> map=new HashMap<String, String>();//根据名称 获取好友id
    private String userName;//选中的 好友名称
    private String showID;//秀场id


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_donation);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void initView(){
        LogUtils.log_E("init view");
        String str="";
        for(int i=0;i<letter.length;i++){
            str=letter[i];
            boolean isAddLetter=false;
            for(int j=0;j<cityLetter.length;j++){
                if(str.equals(cityLetter[j])){
                    if(!isAddLetter){
                        letterToCity.add(str);
                        isAddLetter=true;
                    }
                    letterToCity.add(cityName[j]);
                }
            }
        }


        lv=(ListView)findViewById(R.id.listView1);
        lv.setAdapter(new MyAdapter());
        lv.setOnItemClickListener(this);

        lv1=(ListView)findViewById(R.id.listView2);
        lv1.setAdapter(new MyAdapter1());
        lv1.setOnItemClickListener(this);
        LogUtils.log_E("leesize===" + letterToCity.size());
    }

    public void initData(){
        showID=getIntent().getStringExtra("showID");
        httpUtils=new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.FRIENDLIST_URL + "1", new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    org.json.JSONObject jsonObject = new org.json.JSONObject(responseInfo.result);
                    String status = jsonObject.getString("status");
                    if ("success".equals(status)) {
                        map.clear();
                        FriendsJson friendsJson = JSONObject.parseObject(responseInfo.result, FriendsJson.class);
                        List<FriendsData> list = friendsJson.getData();
                        cityLetter = new String[list.size()];
                        cityName = new String[list.size()];
                        for (int i = 0; i < list.size(); i++) {
                            String name = "";
                            String remarks = list.get(i).getRemarks();
                            if (remarks != null && remarks.trim().length() > 0 && !remarks.trim().equals("-")) {
                                name = remarks;
                            } else {
                                name = list.get(i).getFriends().getNickname();
                            }
                            cityName[i] = name;

                            cityLetter[i] = Utils.getPinYinHeadChar(name);
                            map.put(name, list.get(i).getFriends().getID());
                        }
                        initView();
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        switch (id){
            case R.id.tv_cancle:
                closePopWindow();
                break;
            case R.id.tv_confim:
                String userID=map.get(userName);
                Utils.showToast(map.get(userName));
                donation(userID);
                closePopWindow();
                break;
        }
    }

    //转赠给好友 userID好友id
    public void donation(String userID){
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.DONATIONFRIEND_URL+Constans.userID+"&showID=" + showID + "&touserID=" + userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    org.json.JSONObject jsonObject=new org.json.JSONObject(responseInfo.result);
                    String status=jsonObject.getString("status");
                    if("success".equals(status)){
                        Utils.showToast("转赠成功");
                    }else{
                        String erro=jsonObject.getString("error");
                        if(erro.equals("邀请码已过期")){
                            Utils.showToast("您的邀请函已过期，转赠失败");
                        }
                        LogUtils.log_E("失败原因"+erro);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络异常，转赠失败");
            }
        });
    }



    //关闭 pop
    public void closePopWindow(){
        if (popupWindow!=null){
            popupWindow.dismiss();
        }
    }


    class MyAdapter1 extends BaseAdapter {

        @Override
        public int getCount() {
            return letter.length;
        }

        @Override
        public Object getItem(int position) {
            return letter[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view= LayoutInflater.from(DonationActivity.this).inflate(R.layout.letter_list, null);
            TextView tv=(TextView)view.findViewById(R.id.letterListTextView);
            tv.setText(letter[position]);
            return view;
        }

    }

    class MyAdapter extends BaseAdapter{

        final static int TYPE_1=1;
        final static int TYPE_2=2;

        @Override
        public int getCount() {
            return letterToCity.size();
        }

        @Override
        public Object getItem(int position) {
            return letterToCity.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getItemViewType(int position) {
            for(int i=0;i<letter.length;i++){
                if(letterToCity.get(position).equals(letter[i])){
                    return TYPE_1;
                }
            }
            return TYPE_2;
        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /**
             * 即使convertView缓存了一些布局，但是在重构时，根本不知道怎么样去让convertView返回你所需要的布局，这时你需
             * 要让adapter知道我当前有哪些布局，我重构Item时的布局选取规则，好让convertView能返回你需要的布局。
             * 需要重写以下两个函数
             * @Override
             * public int getItemViewType(int position) {}这个函数获取在getView中创建的视图的类型
             * @Override
             * public int getViewTypeCount() {}返回在getView中创建视图类型的数量
             * 至于这两个方法的详细用处，自己看api即可
             */
            ViewHolder1 vh1=null;
            ViewHolder2 vh2=null;
            int type=getItemViewType(position);
            if(convertView==null){
                switch (type) {
                    case TYPE_1:
                        convertView=LayoutInflater.from(DonationActivity.this).inflate(R.layout.letter, null);
                        vh1=new ViewHolder1();
                        vh1.tv=(TextView)convertView.findViewById(R.id.letterTextView);
                        convertView.setTag(vh1);
                        break;
                    case TYPE_2:
                        convertView=LayoutInflater.from(DonationActivity.this).inflate(R.layout.item_friend, null);
                        vh2=new ViewHolder2();
                        vh2.tv=(TextView)convertView.findViewById(R.id.tv_name);
                        convertView.setTag(vh2);
                        break;
                    default:
                        break;
                }
            }else{
                switch (type) {
                    case TYPE_1:
                        vh1=(ViewHolder1)convertView.getTag();
                        break;
                    case TYPE_2:
                        vh2=(ViewHolder2)convertView.getTag();
                        break;
                    default:
                        break;
                }
            }
            switch (type) {
                case TYPE_1:
                    vh1.tv.setText(letterToCity.get(position));
                    vh1.tv.setTextColor(Color.WHITE);
                    break;
                case TYPE_2:
                    vh2.tv.setText(letterToCity.get(position));
                    break;
                default:
                    break;
            }
            return convertView;

            //此方法不可取，刷新时view会刷新
//			boolean isLetter=false;
//			for(int i=0;i<letter.length;i++){
//				if(letterToCity.get(position).equals(letter[i])){
//					isLetter=true;
//					break;
//				}
//			}
//			ViewHolder vh=null;
//			if(convertView==null){
//				vh=new ViewHolder();
//				if(isLetter){
//					convertView=LayoutInflater.from(MainActivity.this).inflate(R.layout.letter, null);
//					vh.tv=(TextView)convertView.findViewById(R.id.letterTextView);
//				}else{
//					convertView=LayoutInflater.from(MainActivity.this).inflate(R.layout.city, null);
//					vh.tv=(TextView)convertView.findViewById(R.id.cityTextView);
//				}
//				convertView.setTag(vh);
//			}else{
//				vh = (ViewHolder) convertView.getTag();
//			}
//			vh.tv.setText(letterToCity.get(position));
//			return convertView;

            //城市列表，修改布局
//			boolean isLetter=false;
//			for(int i=0;i<letter.length;i++){
//				if(letterToCity.get(position).equals(letter[i])){
//					isLetter=true;
//					break;
//				}
//			}
//			View view;
//			ViewHolder vh;
//			if(convertView==null){
//				view=LayoutInflater.from(MainActivity.this).inflate(R.layout.letter_city, null);
//				vh=new ViewHolder();
//				vh.tv=(TextView)view.findViewById(R.id.letterTextView);
//				vh.ll=(LinearLayout)view.findViewById(R.id.ll);
//				convertView=view;
//				convertView.setTag(vh);
//			}else{
//				view=(View)convertView;
//				vh=(ViewHolder)convertView.getTag();
//			}
//			vh.tv.setText(letterToCity.get(position));
//			if(isLetter){
//				vh.ll.setBackgroundColor(Color.LTGRAY);
//				vh.tv.setPadding(5, 5, vh.tv.getPaddingRight(), 5);
//			}else{
//				vh.ll.setBackgroundColor(Color.WHITE);
//				vh.tv.setPadding(10, 10, vh.tv.getPaddingRight(), 10);
//			}
// 			return view;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        switch (parent.getId()) {
            case R.id.listView1:
                boolean  isLetter=false;
                for(int i=0;i<letter.length;i++){
                    if(letter[i].equals(letterToCity.get(position))){
                        isLetter=true;
                        break;
                    }
                }
                if(!isLetter){
                    userName=parent.getItemAtPosition(position).toString();
                    showPopup(view);
                }
                break;
            case R.id.listView2:
                for(int i=0;i<letterToCity.size();i++){
                    if(letter[position].equals(letterToCity.get(i))){
                        lv.setSelection(i);
                        break;
                    }
                }
                break;
            default:
                break;
        }
    }
    //显示 弹框
    PopupWindow popupWindow=null;
    public void showPopup(View view){
        popupWindow=new PopupWindow(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        View v=View.inflate(this,R.layout.pop_zhuanzeng_friends,null);
        v.findViewById(R.id.tv_cancle).setOnClickListener(this);
        v.findViewById(R.id.tv_confim).setOnClickListener(this);
        popupWindow.setContentView(v);
        popupWindow.showAtLocation(view, Gravity.CENTER,0,0);
    }
    //处理返回键
    public void back(View view){
        startActivity(new Intent(this,MyTicketActivity.class));
        finish();

    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(this,MyTicketActivity.class));
        finish();
    }
}

class ViewHolder{
    TextView tv;
    LinearLayout ll;
}
class ViewHolder1{
    TextView tv;
}
class ViewHolder2{
    TextView tv;
}
